using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// SOP（标准作业程序）写作服务实现
    /// </summary>
    public class SOPWritingService : ISOPWritingService
    {
        private readonly IAIService _aiService;
        private readonly IFileFormatService _fileFormatService;
        private readonly ILogger<SOPWritingService> _logger;

        public SOPWritingService(
            IAIService aiService,
            IFileFormatService fileFormatService,
            ILogger<SOPWritingService> logger)
        {
            _aiService = aiService;
            _fileFormatService = fileFormatService;
            _logger = logger;
        }

        /// <summary>
        /// 分析素材文件，提取业务流程和操作要点
        /// </summary>
        public async Task<SOPMaterialAnalysisResult> AnalyzeMaterialsAsync(
            List<string> materialFiles,
            CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation($"开始分析 {materialFiles.Count} 个素材文件");

                var allContent = new StringBuilder();
                foreach (var filePath in materialFiles)
                {
                    if (File.Exists(filePath))
                    {
                        var content = await _fileFormatService.ReadContentAsync(filePath);
                        allContent.AppendLine($"=== 文件: {Path.GetFileName(filePath)} ===");
                        allContent.AppendLine(content);
                        allContent.AppendLine();
                    }
                }

                var analysisPrompt = BuildMaterialAnalysisPrompt(allContent.ToString());
                var analysisResponse = await _aiService.GenerateTextAsync(analysisPrompt, 3000, 0.6f);

                var result = ParseMaterialAnalysis(analysisResponse);
                _logger.LogInformation($"素材分析完成，识别出 {result.MainProcesses.Count} 个主要流程");

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析素材文件时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成SOP大纲
        /// </summary>
        public async Task<SOPOutline> GenerateOutlineAsync(
            SOPGenerationRequest request,
            SOPMaterialAnalysisResult materialAnalysis,
            CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation("开始生成SOP大纲");

                var outlinePrompt = BuildOutlineGenerationPrompt(request, materialAnalysis);
                var outlineResponse = await _aiService.GenerateTextAsync(outlinePrompt, 2500, 0.7f);

                var outline = ParseSOPOutline(outlineResponse, request);
                
                // 分配字数
                AllocateWordCounts(outline, request.TargetWordCount);

                _logger.LogInformation($"SOP大纲生成完成，包含 {outline.SectionOutlines.Count} 个章节");
                return outline;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成SOP大纲时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成SOP标题
        /// </summary>
        public async Task<string> GenerateTitleAsync(
            SOPGenerationRequest request,
            SOPMaterialAnalysisResult materialAnalysis,
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(request.Title))
                {
                    return request.Title;
                }

                _logger.LogInformation("开始生成SOP标题");

                var titlePrompt = BuildTitleGenerationPrompt(request, materialAnalysis);
                var titleResponse = await _aiService.GenerateTextAsync(titlePrompt, 500, 0.5f);

                var title = titleResponse.Trim().Trim('"', '\'', '《', '》');
                _logger.LogInformation($"SOP标题生成完成: {title}");

                return title;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成SOP标题时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成SOP章节内容
        /// </summary>
        public async Task<string> GenerateSectionAsync(
            SOPSectionOutline sectionOutline,
            SOPGenerationRequest request,
            SOPMaterialAnalysisResult materialAnalysis,
            List<SOPSection> previousSections,
            CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation($"开始生成章节: {sectionOutline.Title}");

                var sectionPrompt = BuildSectionGenerationPrompt(
                    sectionOutline, request, materialAnalysis, previousSections);
                
                var maxTokens = Math.Max(sectionOutline.EstimatedWordCount + 500, 1000);
                var sectionContent = await _aiService.GenerateTextAsync(sectionPrompt, maxTokens, 0.7f);

                _logger.LogInformation($"章节 {sectionOutline.Title} 生成完成，字数: {CountWords(sectionContent)}");
                return sectionContent.Trim();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"生成章节 {sectionOutline.Title} 时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成完整SOP文档
        /// </summary>
        public async Task<SOPGenerationResult> GenerateSOPAsync(
            SOPGenerationRequest request,
            IProgress<string>? progress = null,
            CancellationToken cancellationToken = default)
        {
            var result = new SOPGenerationResult();
            var stopwatch = Stopwatch.StartNew();

            try
            {
                _logger.LogInformation("开始生成完整SOP文档");

                // 1. 分析素材文件
                progress?.Report("正在分析素材文件...");
                var materialAnalysis = await AnalyzeMaterialsAsync(request.MaterialFiles, cancellationToken);

                // 2. 生成SOP标题
                progress?.Report("正在生成SOP标题...");
                var title = await GenerateTitleAsync(request, materialAnalysis, cancellationToken);
                result.Title = title;

                // 3. 生成SOP大纲
                progress?.Report("正在生成SOP大纲...");
                var outline = await GenerateOutlineAsync(request, materialAnalysis, cancellationToken);

                // 4. 生成各章节内容
                var sections = new List<SOPSection>();
                for (int i = 0; i < outline.SectionOutlines.Count; i++)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var sectionOutline = outline.SectionOutlines[i];
                    progress?.Report($"正在生成章节: {sectionOutline.Title} ({i + 1}/{outline.SectionOutlines.Count})");

                    var sectionContent = await GenerateSectionAsync(
                        sectionOutline, request, materialAnalysis, sections, cancellationToken);

                    var section = new SOPSection
                    {
                        Title = sectionOutline.Title,
                        Content = sectionContent,
                        SectionType = sectionOutline.SectionType,
                        WordCount = CountWords(sectionContent),
                        Order = sectionOutline.Order
                    };

                    sections.Add(section);

                    // 添加延迟避免API限制
                    if (i < outline.SectionOutlines.Count - 1)
                    {
                        await Task.Delay(1000, cancellationToken);
                    }
                }

                // 5. 格式化SOP内容
                progress?.Report("正在格式化SOP内容...");
                var formattedContent = FormatSOPContent(sections, request, title);

                // 6. 设置结果
                result.IsSuccess = true;
                result.Content = formattedContent;
                result.Sections = sections;
                result.Statistics = new SOPGenerationStatistics
                {
                    TotalWordCount = CountWords(formattedContent),
                    GenerationTime = stopwatch.Elapsed,
                    MaterialFilesCount = request.MaterialFiles.Count,
                    SectionsCount = sections.Count,
                    MaterialUtilizationRate = CalculateMaterialUtilization(materialAnalysis, sections)
                };

                _logger.LogInformation($"SOP生成完成，总字数: {result.Statistics.TotalWordCount}, 耗时: {stopwatch.Elapsed}");
                return result;
            }
            catch (OperationCanceledException)
            {
                _logger.LogInformation("SOP生成被用户取消");
                result.IsSuccess = false;
                result.ErrorMessage = "生成已取消";
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成SOP时发生错误");
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
                return result;
            }
            finally
            {
                stopwatch.Stop();
            }
        }

        /// <summary>
        /// 格式化SOP内容
        /// </summary>
        public string FormatSOPContent(List<SOPSection> sections, SOPGenerationRequest request, string title)
        {
            var content = new StringBuilder();

            // 文档头部
            content.AppendLine($"# {title}");
            content.AppendLine();
            
            // 文档信息
            content.AppendLine("## 文档信息");
            content.AppendLine();
            content.AppendLine($"- **文档类型**: {request.SOPType}");
            content.AppendLine($"- **业务领域**: {request.BusinessDomain}");
            if (!string.IsNullOrEmpty(request.Department))
                content.AppendLine($"- **所属部门**: {request.Department}");
            if (!string.IsNullOrEmpty(request.Author))
                content.AppendLine($"- **制定人**: {request.Author}");
            if (!string.IsNullOrEmpty(request.Reviewer))
                content.AppendLine($"- **审核人**: {request.Reviewer}");
            if (!string.IsNullOrEmpty(request.Approver))
                content.AppendLine($"- **批准人**: {request.Approver}");
            content.AppendLine($"- **生成时间**: {DateTime.Now:yyyy年MM月dd日}");
            content.AppendLine();

            // 各章节内容
            foreach (var section in sections.OrderBy(s => s.Order))
            {
                content.AppendLine($"## {section.Title}");
                content.AppendLine();
                content.AppendLine(section.Content);
                content.AppendLine();
            }

            return content.ToString();
        }

        /// <summary>
        /// 验证SOP质量
        /// </summary>
        public async Task<int> ValidateSOPQualityAsync(string content, SOPGenerationRequest request)
        {
            try
            {
                var validationPrompt = BuildQualityValidationPrompt(content, request);
                var validationResponse = await _aiService.GenerateTextAsync(validationPrompt, 1000, 0.3f);

                // 尝试从响应中提取评分
                var lines = validationResponse.Split('\n', StringSplitOptions.RemoveEmptyEntries);
                foreach (var line in lines)
                {
                    if (line.Contains("评分") || line.Contains("分数"))
                    {
                        var numbers = System.Text.RegularExpressions.Regex.Matches(line, @"\d+");
                        if (numbers.Count > 0 && int.TryParse(numbers[0].Value, out var score))
                        {
                            return Math.Min(Math.Max(score, 0), 100);
                        }
                    }
                }

                // 默认评分
                return 75;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证SOP质量时发生错误");
                return 70; // 默认评分
            }
        }

        #region 私有辅助方法

        /// <summary>
        /// 构建素材分析提示词
        /// </summary>
        private string BuildMaterialAnalysisPrompt(string materialContent)
        {
            return $@"请深入分析以下素材内容，提取SOP（标准作业程序）相关的关键信息：

素材内容：
{materialContent}

请从以下维度进行分析，并以JSON格式返回结果：

1. **主要业务流程** (main_processes): 识别核心业务流程和工作流
2. **关键操作步骤** (key_operations): 提取具体的操作步骤和方法
3. **质量控制点** (quality_control_points): 识别质量检查和控制要点
4. **风险识别点** (risk_points): 识别潜在风险和注意事项
5. **角色和职责** (roles_responsibilities): 提取相关角色和职责分工
6. **关键术语** (key_terms): 识别专业术语和定义
7. **相关标准** (standards): 提取相关标准、规范和要求
8. **工具设备** (tools_equipment): 识别所需工具、设备和资源
9. **输入输出** (input_output): 识别输入要求和输出标准
10. **性能指标** (performance_indicators): 提取绩效指标和评估标准

返回格式示例：
{{
  ""main_processes"": [""流程1"", ""流程2""],
  ""key_operations"": [""操作1"", ""操作2""],
  ""quality_control_points"": [""控制点1"", ""控制点2""],
  ""risk_points"": [""风险点1"", ""风险点2""],
  ""roles_responsibilities"": [""角色职责1"", ""角色职责2""],
  ""key_terms"": [""术语1"", ""术语2""],
  ""standards"": [""标准1"", ""标准2""],
  ""tools_equipment"": [""工具1"", ""工具2""],
  ""input_output"": [""要求1"", ""要求2""],
  ""performance_indicators"": [""指标1"", ""指标2""]
}}

请确保分析全面、准确，重点关注可操作性和标准化要求。";
        }

        /// <summary>
        /// 解析素材分析结果
        /// </summary>
        private SOPMaterialAnalysisResult ParseMaterialAnalysis(string analysisResponse)
        {
            var result = new SOPMaterialAnalysisResult();

            try
            {
                // 尝试解析JSON格式
                var jsonStart = analysisResponse.IndexOf('{');
                var jsonEnd = analysisResponse.LastIndexOf('}');
                
                if (jsonStart >= 0 && jsonEnd > jsonStart)
                {
                    var jsonContent = analysisResponse.Substring(jsonStart, jsonEnd - jsonStart + 1);
                    var analysisData = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(jsonContent);

                    if (analysisData != null)
                    {
                        result.MainProcesses = ExtractStringList(analysisData, "main_processes");
                        result.KeyOperations = ExtractStringList(analysisData, "key_operations");
                        result.QualityControlPoints = ExtractStringList(analysisData, "quality_control_points");
                        result.RiskPoints = ExtractStringList(analysisData, "risk_points");
                        result.RolesAndResponsibilities = ExtractStringList(analysisData, "roles_responsibilities");
                        result.KeyTerms = ExtractStringList(analysisData, "key_terms");
                        result.Standards = ExtractStringList(analysisData, "standards");
                        result.ToolsAndEquipment = ExtractStringList(analysisData, "tools_equipment");
                        result.InputOutputRequirements = ExtractStringList(analysisData, "input_output");
                        result.PerformanceIndicators = ExtractStringList(analysisData, "performance_indicators");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析JSON格式的分析结果失败，使用文本解析");
            }

            // 如果JSON解析失败，使用文本解析作为备选
            if (result.MainProcesses.Count == 0)
            {
                ParseAnalysisFromText(analysisResponse, result);
            }

            return result;
        }

        /// <summary>
        /// 从JSON数据中提取字符串列表
        /// </summary>
        private List<string> ExtractStringList(Dictionary<string, JsonElement> data, string key)
        {
            if (data.TryGetValue(key, out var element) && element.ValueKind == JsonValueKind.Array)
            {
                return element.EnumerateArray()
                    .Where(e => e.ValueKind == JsonValueKind.String)
                    .Select(e => e.GetString()!)
                    .Where(s => !string.IsNullOrWhiteSpace(s))
                    .ToList();
            }
            return new List<string>();
        }

        /// <summary>
        /// 从文本中解析分析结果（备选方案）
        /// </summary>
        private void ParseAnalysisFromText(string text, SOPMaterialAnalysisResult result)
        {
            var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            
            foreach (var line in lines)
            {
                var trimmedLine = line.Trim();
                if (trimmedLine.Contains("流程") || trimmedLine.Contains("工作流"))
                {
                    result.MainProcesses.Add(trimmedLine);
                }
                else if (trimmedLine.Contains("操作") || trimmedLine.Contains("步骤"))
                {
                    result.KeyOperations.Add(trimmedLine);
                }
                else if (trimmedLine.Contains("质量") || trimmedLine.Contains("控制"))
                {
                    result.QualityControlPoints.Add(trimmedLine);
                }
                else if (trimmedLine.Contains("风险") || trimmedLine.Contains("注意"))
                {
                    result.RiskPoints.Add(trimmedLine);
                }
            }

            // 确保至少有一些基本内容
            if (result.MainProcesses.Count == 0)
            {
                result.MainProcesses.Add("标准业务流程");
            }
            if (result.KeyOperations.Count == 0)
            {
                result.KeyOperations.Add("关键操作步骤");
            }
        }

        /// <summary>
        /// 统计字数
        /// </summary>
        private int CountWords(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return 0;

            // 统计中文字符数
            return text.Where(c => c >= 0x4e00 && c <= 0x9fff).Count();
        }

        /// <summary>
        /// 计算素材利用率
        /// </summary>
        private double CalculateMaterialUtilization(SOPMaterialAnalysisResult materialAnalysis, List<SOPSection> sections)
        {
            var totalAnalysisItems = materialAnalysis.MainProcesses.Count +
                                   materialAnalysis.KeyOperations.Count +
                                   materialAnalysis.QualityControlPoints.Count +
                                   materialAnalysis.RiskPoints.Count;

            if (totalAnalysisItems == 0) return 0.0;

            var utilizedItems = 0;
            var allSectionContent = string.Join(" ", sections.Select(s => s.Content));

            foreach (var process in materialAnalysis.MainProcesses)
            {
                if (allSectionContent.Contains(process.Substring(0, Math.Min(process.Length, 10))))
                    utilizedItems++;
            }

            return (double)utilizedItems / totalAnalysisItems * 100;
        }

        /// <summary>
        /// 构建大纲生成提示词
        /// </summary>
        private string BuildOutlineGenerationPrompt(SOPGenerationRequest request, SOPMaterialAnalysisResult materialAnalysis)
        {
            var processesInfo = string.Join("\n", materialAnalysis.MainProcesses.Select(p => $"- {p}"));
            var operationsInfo = string.Join("\n", materialAnalysis.KeyOperations.Select(o => $"- {o}"));

            return $@"请为以下SOP（标准作业程序）生成详细的章节大纲：

SOP基本信息：
- 类型：{request.SOPType}
- 业务领域：{request.BusinessDomain}
- 目标字数：{request.TargetWordCount}字
- 详细程度：{request.DetailLevel:F1}
- 规范化程度：{request.StandardizationLevel:F1}

主要业务流程：
{processesInfo}

关键操作步骤：
{operationsInfo}

SOP结构要求：
- 包含目的和范围：{request.Structure.IncludePurposeAndScope}
- 包含职责分工：{request.Structure.IncludeResponsibilities}
- 包含操作流程：{request.Structure.IncludeProcedures}
- 包含质量控制：{request.Structure.IncludeQualityControl}
- 包含风险控制：{request.Structure.IncludeRiskControl}
- 包含记录管理：{request.Structure.IncludeRecordManagement}
- 包含培训要求：{request.Structure.IncludeTrainingRequirements}
- 包含相关文件：{request.Structure.IncludeRelatedDocuments}
- 包含附录：{request.Structure.IncludeAppendices}
- 包含修订历史：{request.Structure.IncludeRevisionHistory}

请生成包含以下信息的章节大纲：
1. 章节标题
2. 章节类型（如：目的范围、职责分工、操作流程、质量控制等）
3. 章节要点（3-5个关键要点）
4. 章节顺序

要求：
1. 大纲要符合{request.SOPType}的标准格式
2. 体现{request.BusinessDomain}领域的专业特点
3. 确保逻辑清晰、结构完整
4. 突出操作性和可执行性
5. 符合ISO 9001等质量管理体系要求

请按以下格式返回：
章节1：
标题：[章节标题]
类型：[章节类型]
要点：
- [要点1]
- [要点2]
- [要点3]

章节2：
...";
        }

        /// <summary>
        /// 解析SOP大纲
        /// </summary>
        private SOPOutline ParseSOPOutline(string outlineResponse, SOPGenerationRequest request)
        {
            var outline = new SOPOutline();
            var sections = new List<SOPSectionOutline>();

            var lines = outlineResponse.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            SOPSectionOutline? currentSection = null;
            var order = 1;

            foreach (var line in lines)
            {
                var trimmedLine = line.Trim();

                if (trimmedLine.StartsWith("章节") && trimmedLine.Contains("："))
                {
                    // 保存前一个章节
                    if (currentSection != null)
                    {
                        currentSection.Order = order++;
                        sections.Add(currentSection);
                    }

                    // 开始新章节
                    currentSection = new SOPSectionOutline();
                }
                else if (trimmedLine.StartsWith("标题：") && currentSection != null)
                {
                    currentSection.Title = trimmedLine.Substring(3).Trim();
                }
                else if (trimmedLine.StartsWith("类型：") && currentSection != null)
                {
                    currentSection.SectionType = trimmedLine.Substring(3).Trim();
                }
                else if (trimmedLine.StartsWith("- ") && currentSection != null)
                {
                    currentSection.KeyPoints.Add(trimmedLine.Substring(2).Trim());
                }
            }

            // 添加最后一个章节
            if (currentSection != null)
            {
                currentSection.Order = order;
                sections.Add(currentSection);
            }

            // 如果解析失败，使用默认结构
            if (sections.Count == 0)
            {
                sections = GenerateDefaultSOPStructure(request);
            }

            outline.SectionOutlines = sections;
            return outline;
        }

        /// <summary>
        /// 生成默认SOP结构
        /// </summary>
        private List<SOPSectionOutline> GenerateDefaultSOPStructure(SOPGenerationRequest request)
        {
            var sections = new List<SOPSectionOutline>();
            var order = 1;

            if (request.Structure.IncludePurposeAndScope)
            {
                sections.Add(new SOPSectionOutline
                {
                    Title = "目的和范围",
                    SectionType = "目的范围",
                    KeyPoints = new List<string> { "明确SOP的目的", "定义适用范围", "说明使用对象" },
                    Order = order++
                });
            }

            if (request.Structure.IncludeResponsibilities)
            {
                sections.Add(new SOPSectionOutline
                {
                    Title = "职责分工",
                    SectionType = "职责分工",
                    KeyPoints = new List<string> { "定义各角色职责", "明确权限范围", "建立责任机制" },
                    Order = order++
                });
            }

            if (request.Structure.IncludeProcedures)
            {
                sections.Add(new SOPSectionOutline
                {
                    Title = "操作流程",
                    SectionType = "操作流程",
                    KeyPoints = new List<string> { "详细操作步骤", "流程图说明", "关键控制点" },
                    Order = order++
                });
            }

            if (request.Structure.IncludeQualityControl)
            {
                sections.Add(new SOPSectionOutline
                {
                    Title = "质量控制",
                    SectionType = "质量控制",
                    KeyPoints = new List<string> { "质量标准", "检查要点", "纠正措施" },
                    Order = order++
                });
            }

            if (request.Structure.IncludeRiskControl)
            {
                sections.Add(new SOPSectionOutline
                {
                    Title = "风险控制",
                    SectionType = "风险控制",
                    KeyPoints = new List<string> { "风险识别", "预防措施", "应急处理" },
                    Order = order++
                });
            }

            if (request.Structure.IncludeRecordManagement)
            {
                sections.Add(new SOPSectionOutline
                {
                    Title = "记录管理",
                    SectionType = "记录管理",
                    KeyPoints = new List<string> { "记录要求", "保存期限", "归档管理" },
                    Order = order++
                });
            }

            if (request.Structure.IncludeTrainingRequirements)
            {
                sections.Add(new SOPSectionOutline
                {
                    Title = "培训要求",
                    SectionType = "培训要求",
                    KeyPoints = new List<string> { "培训内容", "培训方式", "考核标准" },
                    Order = order++
                });
            }

            if (request.Structure.IncludeRelatedDocuments)
            {
                sections.Add(new SOPSectionOutline
                {
                    Title = "相关文件",
                    SectionType = "相关文件",
                    KeyPoints = new List<string> { "引用标准", "相关制度", "参考文件" },
                    Order = order++
                });
            }

            if (request.Structure.IncludeAppendices)
            {
                sections.Add(new SOPSectionOutline
                {
                    Title = "附录",
                    SectionType = "附录",
                    KeyPoints = new List<string> { "表格模板", "检查清单", "流程图" },
                    Order = order++
                });
            }

            if (request.Structure.IncludeRevisionHistory)
            {
                sections.Add(new SOPSectionOutline
                {
                    Title = "修订历史",
                    SectionType = "修订历史",
                    KeyPoints = new List<string> { "版本信息", "修订内容", "修订日期" },
                    Order = order++
                });
            }

            return sections;
        }

        /// <summary>
        /// 分配字数
        /// </summary>
        private void AllocateWordCounts(SOPOutline outline, int targetWordCount)
        {
            var totalSections = outline.SectionOutlines.Count;
            if (totalSections == 0) return;

            // 预留10%给标题和格式
            var availableWordCount = (int)(targetWordCount * 0.9);

            // 根据章节类型分配权重
            var weights = new Dictionary<string, double>
            {
                { "目的范围", 0.8 },
                { "职责分工", 1.0 },
                { "操作流程", 2.5 },
                { "质量控制", 1.5 },
                { "风险控制", 1.5 },
                { "记录管理", 1.0 },
                { "培训要求", 1.2 },
                { "相关文件", 0.8 },
                { "附录", 1.0 },
                { "修订历史", 0.5 }
            };

            var totalWeight = outline.SectionOutlines.Sum(s => weights.GetValueOrDefault(s.SectionType, 1.0));

            foreach (var section in outline.SectionOutlines)
            {
                var weight = weights.GetValueOrDefault(section.SectionType, 1.0);
                section.EstimatedWordCount = (int)(availableWordCount * weight / totalWeight);

                // 确保最小字数
                section.EstimatedWordCount = Math.Max(section.EstimatedWordCount, 200);
            }

            outline.EstimatedTotalWordCount = outline.SectionOutlines.Sum(s => s.EstimatedWordCount);
        }

        /// <summary>
        /// 构建标题生成提示词
        /// </summary>
        private string BuildTitleGenerationPrompt(SOPGenerationRequest request, SOPMaterialAnalysisResult materialAnalysis)
        {
            var processesInfo = string.Join("、", materialAnalysis.MainProcesses.Take(3));

            return $@"请为以下SOP（标准作业程序）生成专业的标题：

SOP信息：
- 类型：{request.SOPType}
- 业务领域：{request.BusinessDomain}
- 主要流程：{processesInfo}

要求：
1. 标题要准确反映SOP的核心内容
2. 符合{request.BusinessDomain}领域的专业规范
3. 简洁明了，一般不超过25个字
4. 体现{request.SOPType}的特点
5. 使用标准的SOP命名格式
6. 只返回标题，不要其他解释

请生成3个候选标题，选择最佳的一个返回。";
        }

        /// <summary>
        /// 构建章节生成提示词
        /// </summary>
        private string BuildSectionGenerationPrompt(
            SOPSectionOutline sectionOutline,
            SOPGenerationRequest request,
            SOPMaterialAnalysisResult materialAnalysis,
            List<SOPSection> previousSections)
        {
            var keyPointsInfo = string.Join("\n", sectionOutline.KeyPoints.Select(p => $"- {p}"));
            var previousContent = previousSections.Count > 0
                ? string.Join("\n\n", previousSections.TakeLast(2).Select(s => $"{s.Title}:\n{s.Content.Substring(0, Math.Min(s.Content.Length, 300))}..."))
                : "无";

            var relevantProcesses = string.Join("\n", materialAnalysis.MainProcesses.Select(p => $"- {p}"));
            var relevantOperations = string.Join("\n", materialAnalysis.KeyOperations.Select(o => $"- {o}"));
            var qualityPoints = string.Join("\n", materialAnalysis.QualityControlPoints.Select(q => $"- {q}"));
            var riskPoints = string.Join("\n", materialAnalysis.RiskPoints.Select(r => $"- {r}"));

            var userRequirementsSection = !string.IsNullOrWhiteSpace(request.UserRequirements)
                ? $@"

用户特殊要求：
{request.UserRequirements}"
                : "";

            return $@"请为SOP生成以下章节的详细内容：

章节信息：
- 标题：{sectionOutline.Title}
- 类型：{sectionOutline.SectionType}
- 目标字数：约{sectionOutline.EstimatedWordCount}字

章节要点：
{keyPointsInfo}

SOP背景：
- 类型：{request.SOPType}
- 业务领域：{request.BusinessDomain}
- 详细程度：{request.DetailLevel:F1}
- 规范化程度：{request.StandardizationLevel:F1}

相关素材信息：
主要业务流程：
{relevantProcesses}

关键操作步骤：
{relevantOperations}

质量控制点：
{qualityPoints}

风险识别点：
{riskPoints}

前面章节内容（供参考）：
{previousContent}{userRequirementsSection}

写作要求：
1. 内容要符合{request.SOPType}的标准格式
2. 语言要专业、准确、简洁
3. 逻辑清晰，条理分明
4. 与前面章节保持连贯性
5. 充分利用提供的素材信息
6. 字数控制在{sectionOutline.EstimatedWordCount}字左右
7. 突出可操作性和标准化要求
8. 符合ISO 9001等质量管理体系标准
9. 使用编号、表格等格式增强可读性
10. 包含具体的执行标准和检查要点
11. 严格遵循用户的特殊要求（如有）

请生成专业、规范的SOP章节内容。";
        }

        /// <summary>
        /// 构建质量验证提示词
        /// </summary>
        private string BuildQualityValidationPrompt(string content, SOPGenerationRequest request)
        {
            return $@"请评估以下SOP（标准作业程序）的质量，并给出0-100的评分：

SOP类型：{request.SOPType}
业务领域：{request.BusinessDomain}

SOP内容：
{content.Substring(0, Math.Min(content.Length, 2000))}...

评估维度：
1. **完整性** (25分)：是否包含必要的章节和内容
2. **准确性** (25分)：技术内容是否准确、专业
3. **可操作性** (25分)：步骤是否清晰、可执行
4. **规范性** (25分)：是否符合SOP标准格式

请从以上四个维度进行评估，并给出总评分。

评分标准：
- 90-100分：优秀，完全符合专业SOP标准
- 80-89分：良好，基本符合要求，有少量改进空间
- 70-79分：合格，满足基本要求，需要一定改进
- 60-69分：需要改进，存在明显不足
- 60分以下：不合格，需要重新编写

请返回具体评分和简要评价。";
        }

        /// <summary>
        /// 生成流程图描述
        /// </summary>
        public async Task<string> GenerateFlowchartDescriptionAsync(
            SOPMaterialAnalysisResult materialAnalysis,
            SOPGenerationRequest request,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var flowchartPrompt = BuildFlowchartPrompt(materialAnalysis, request);
                var flowchartResponse = await _aiService.GenerateTextAsync(flowchartPrompt, 1500, 0.6f);
                return flowchartResponse.Trim();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成流程图描述时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成检查清单
        /// </summary>
        public async Task<string> GenerateChecklistAsync(
            SOPMaterialAnalysisResult materialAnalysis,
            SOPGenerationRequest request,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var checklistPrompt = BuildChecklistPrompt(materialAnalysis, request);
                var checklistResponse = await _aiService.GenerateTextAsync(checklistPrompt, 1500, 0.6f);
                return checklistResponse.Trim();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成检查清单时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成风险评估表
        /// </summary>
        public async Task<string> GenerateRiskAssessmentAsync(
            SOPMaterialAnalysisResult materialAnalysis,
            SOPGenerationRequest request,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var riskPrompt = BuildRiskAssessmentPrompt(materialAnalysis, request);
                var riskResponse = await _aiService.GenerateTextAsync(riskPrompt, 1500, 0.6f);
                return riskResponse.Trim();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成风险评估表时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成培训计划
        /// </summary>
        public async Task<string> GenerateTrainingPlanAsync(
            SOPMaterialAnalysisResult materialAnalysis,
            SOPGenerationRequest request,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var trainingPrompt = BuildTrainingPlanPrompt(materialAnalysis, request);
                var trainingResponse = await _aiService.GenerateTextAsync(trainingPrompt, 1500, 0.6f);
                return trainingResponse.Trim();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成培训计划时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成绩效指标
        /// </summary>
        public async Task<string> GeneratePerformanceIndicatorsAsync(
            SOPMaterialAnalysisResult materialAnalysis,
            SOPGenerationRequest request,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var performancePrompt = BuildPerformanceIndicatorsPrompt(materialAnalysis, request);
                var performanceResponse = await _aiService.GenerateTextAsync(performancePrompt, 1500, 0.6f);
                return performanceResponse.Trim();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成绩效指标时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 构建流程图提示词
        /// </summary>
        private string BuildFlowchartPrompt(SOPMaterialAnalysisResult materialAnalysis, SOPGenerationRequest request)
        {
            var processes = string.Join("\n", materialAnalysis.MainProcesses.Select(p => $"- {p}"));
            var operations = string.Join("\n", materialAnalysis.KeyOperations.Select(o => $"- {o}"));

            return $@"请为以下SOP生成详细的流程图描述：

业务领域：{request.BusinessDomain}
SOP类型：{request.SOPType}

主要业务流程：
{processes}

关键操作步骤：
{operations}

请生成包含以下内容的流程图描述：
1. 流程起点和终点
2. 主要决策点
3. 关键操作步骤
4. 质量检查点
5. 异常处理路径
6. 责任人标注

要求：
- 使用标准的流程图符号说明
- 包含详细的步骤描述
- 标注关键控制点
- 体现决策逻辑
- 便于理解和执行";
        }

        /// <summary>
        /// 构建检查清单提示词
        /// </summary>
        private string BuildChecklistPrompt(SOPMaterialAnalysisResult materialAnalysis, SOPGenerationRequest request)
        {
            var qualityPoints = string.Join("\n", materialAnalysis.QualityControlPoints.Select(q => $"- {q}"));
            var operations = string.Join("\n", materialAnalysis.KeyOperations.Select(o => $"- {o}"));

            return $@"请为以下SOP生成详细的检查清单：

业务领域：{request.BusinessDomain}
SOP类型：{request.SOPType}

质量控制点：
{qualityPoints}

关键操作步骤：
{operations}

请生成包含以下内容的检查清单：
1. 准备阶段检查项
2. 执行过程检查项
3. 完成后验证项
4. 质量标准要求
5. 记录要求
6. 异常情况处理

格式要求：
- 使用复选框格式 □
- 每项包含具体检查标准
- 标注责任人
- 包含检查频次
- 便于实际操作使用";
        }

        /// <summary>
        /// 构建风险评估提示词
        /// </summary>
        private string BuildRiskAssessmentPrompt(SOPMaterialAnalysisResult materialAnalysis, SOPGenerationRequest request)
        {
            var riskPoints = string.Join("\n", materialAnalysis.RiskPoints.Select(r => $"- {r}"));
            var operations = string.Join("\n", materialAnalysis.KeyOperations.Select(o => $"- {o}"));

            return $@"请为以下SOP生成详细的风险评估表：

业务领域：{request.BusinessDomain}
SOP类型：{request.SOPType}

已识别风险点：
{riskPoints}

关键操作步骤：
{operations}

请生成包含以下内容的风险评估表：
1. 风险识别
2. 风险等级评估（高/中/低）
3. 可能后果
4. 预防措施
5. 应急处理方案
6. 责任人
7. 监控频次

评估标准：
- 高风险：可能导致严重后果
- 中风险：可能导致一般影响
- 低风险：影响较小或概率很低

格式：使用表格形式，便于查阅和管理";
        }

        /// <summary>
        /// 构建培训计划提示词
        /// </summary>
        private string BuildTrainingPlanPrompt(SOPMaterialAnalysisResult materialAnalysis, SOPGenerationRequest request)
        {
            var operations = string.Join("\n", materialAnalysis.KeyOperations.Select(o => $"- {o}"));
            var roles = string.Join("\n", materialAnalysis.RolesAndResponsibilities.Select(r => $"- {r}"));

            return $@"请为以下SOP生成详细的培训计划：

业务领域：{request.BusinessDomain}
SOP类型：{request.SOPType}

关键操作步骤：
{operations}

相关角色职责：
{roles}

请生成包含以下内容的培训计划：
1. 培训目标
2. 培训对象分类
3. 培训内容大纲
4. 培训方式方法
5. 培训时间安排
6. 考核标准
7. 培训效果评估
8. 持续培训要求

要求：
- 针对不同角色制定差异化培训
- 包含理论和实操培训
- 设定明确的考核标准
- 建立培训档案管理
- 确保培训效果可衡量";
        }

        /// <summary>
        /// 构建绩效指标提示词
        /// </summary>
        private string BuildPerformanceIndicatorsPrompt(SOPMaterialAnalysisResult materialAnalysis, SOPGenerationRequest request)
        {
            var indicators = string.Join("\n", materialAnalysis.PerformanceIndicators.Select(i => $"- {i}"));
            var operations = string.Join("\n", materialAnalysis.KeyOperations.Select(o => $"- {o}"));

            return $@"请为以下SOP生成详细的绩效指标体系：

业务领域：{request.BusinessDomain}
SOP类型：{request.SOPType}

已识别绩效指标：
{indicators}

关键操作步骤：
{operations}

请生成包含以下内容的绩效指标体系：
1. 效率指标
2. 质量指标
3. 成本指标
4. 时间指标
5. 客户满意度指标
6. 合规性指标

每个指标包含：
- 指标名称
- 计算公式
- 目标值
- 数据来源
- 监控频次
- 责任人
- 改进措施

要求：
- 指标要可量化、可测量
- 设定合理的目标值
- 建立监控机制
- 便于持续改进";
        }

        #endregion
    }
}
